import 'package:boss/common/common.dart';
import 'package:boss/main.dart';
import 'package:boss/models/login_user.dart';
import 'package:boss/models/store_message.dart';
import 'package:boss/ui/page/index/index_page.dart';
import 'package:boss/ui/page/login/constant/login_type.dart';
import 'package:boss/ui/page/login/model/cache_user.dart';
import 'package:boss/ui/page/login/page/loginSelectStorePage/login_select_store_page.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class LoginUserProvider extends ChangeNotifier {
  LoginUser loginUser;

  List<StoreMessage> stores = [];

  StoreMessage selectedStore;

  LoginUserProvider() {
    loginUser = CacheUser.usableUser?.loginUser;
  }

  setLoginUser(LoginUser loginUser) {
    this.loginUser = loginUser;
    notifyListeners();
  }

  login(
    BuildContext context, {
    LoginType loginType,
    String storeNo,
    String phone,
    String password,
  }) async {
    if (loginType == LoginType.userPassword) {
      if (storeNo == null || storeNo == '') {
        toast('请输入店铺编号');
        return;
      }
      if (storeNo.length != 7) {
        toast('请输入7位的店铺编号');
        return;
      }
      if (phone == null || phone == '') {
        toast('请输入手机号');
        return;
      }
      if (!RegUtil.testPhone(phone)) {
        toast('请输入正确的手机号');
        return;
      }

      try {
        showLoadingToast();

        var result = await api.login({
          'username': phone,
          'password': StringUtil.md5(password),
          'storeNo': storeNo,
        });

        if (!result.successful()) {
          toast(result.msg);
          return;
        }

        _setUserInfo(context, loginUser: result.data, passWord: password);
      } catch (e) {
        toast(e.toString());
      } finally {
        hideLoadingToast();
      }
    }
  }

  //用户账号密码登录
  newUserLogin(
    BuildContext context, {
    String phone,
    String password,
  }) async {
    if (phone == null || phone == '') {
      toast('请输入手机号');
      return;
    }
    if (!RegUtil.testPhone(phone)) {
      toast('请输入正确的手机号');
      return;
    }
    try {
      showLoadingToast();
      var result = await api.loginByBoss({
        'username': phone,
        'password': StringUtil.md5(password),
      });
      if (!result.successful()) {
        toast(result.msg);
        return;
      }
      loginUser = result.data.userInfo;
      loginUser.passWord = password;
      stores = result.data.storeList;

      if (stores == null || stores.length == 0) {
        toast("当前用户没有门店");
        return;
      }
      if (stores.length == 1) {
        selectedStore = stores[0];
        setUserAnd2Home(context);
      } else {
        Navigator.pushNamed(context, LoginSelectStorePage.pageName);
      }
    } catch (e) {
      toast(Constant.httpServeErrText);
    } finally {
      hideLoadingToast();
    }
  }

  loginByVerifyCode(BuildContext context, {String phone, String code}) async {
    if (phone == null || phone == '') {
      toast('请输入手机号');
      return;
    }
    if (!RegUtil.testPhone(phone)) {
      toast('请输入正确的手机号');
      return;
    }
    if (code == null || code == '') {
      toast('请输入验证码');
      return;
    }
    if (!RegUtil.testCode(code)) {
      toast('请输入正确的验证码');
      return;
    }

    try {
      showLoadingToast();

      var response = await api.loginByCode({
        'phone': phone,
        'verifyCode': code,
      });
      if (!response.successful()) {
        toast(response.msg);
        return;
      }

      stores = response.data.storeList;
      loginUser = response.data.userInfo;

      Navigator.pushNamed(context, LoginSelectStorePage.pageName);
    } catch (e) {
      toast(Constant.httpServeErrText);
    } finally {
      hideLoadingToast();
    }
  }

  updateStoreName(String storeName) {
    loginUser.storeName = storeName;
    notifyListeners();
  }

  setSelectedStore(StoreMessage store) {
    selectedStore = store;
    notifyListeners();
  }

  setUserAnd2Home(BuildContext context) async {
    if (selectedStore == null) {
      toast('请选择店铺');
      return;
    }
    try {
      showLoadingToast();
      loginUser.storeId = selectedStore.storeId;

      var res = await api.authLoginByCode(loginUser);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      _setUserInfo(context, loginUser: res.data, passWord: loginUser.passWord);
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  _setUserInfo(BuildContext context, {@required LoginUser loginUser, @required String passWord}) async {
    this.loginUser = loginUser;
    loginUser.passWord = passWord;
    notifyListeners();

    await CacheUser.cacheUser(CacheUser(
      loginUser: loginUser,
      loginTime: DateTime.now(),
    ));

    TokenInterceptor.token = loginUser.token;

    api.upDevice({'uuid': Constant.uuid, 'jid': Constant.jPushId});

    Navigator.pushNamedAndRemoveUntil(
      context,
      IndexPage.pageName,
      (route) => false,
    );
  }
}
